import java.util.*;
import java.io.*;

public class LogEntry {
    private String time;
    private String type;
    private String operator;
    private String detail;

    // 静态日志列表
    private static List<LogEntry> logs = new ArrayList<>();
    private static final String LOG_FILE = "data/logs.txt";

    static {
        loadLogs();
    }

    public LogEntry(String time, String type, String operator, String detail) {
        this.time = time;
        this.type = type;
        this.operator = operator;
        this.detail = detail;
    }

    public String getTime() { return time; }
    public String getType() { return type; }
    public String getOperator() { return operator; }
    public String getDetail() { return detail; }

    // 静态方法：添加日志
    public static void addLog(LogEntry log) {
        logs.add(log);
        saveLogs();
    }

    // 静态方法：显示日志
    public static void showLogs() {
        if (logs.isEmpty()) {
            System.out.println("暂无操作日志。");
            return;
        }
        System.out.println("\n操作日志:");
        for (LogEntry log : logs) {
            System.out.printf("[%s] %s | %s | %s\n", log.getTime(), log.getType(), log.getOperator(), log.getDetail());
        }
    }

    // 静态方法：获取日志列表
    public static List<LogEntry> getLogs() {
        return logs;
    }
    
    // 文件持久化方法
    private static void saveLogs() {
        try {
            File dataDir = new File("data");
            if (!dataDir.exists()) {
                dataDir.mkdirs();
            }
            
            FileWriter writer = new FileWriter(LOG_FILE);
            for (LogEntry log : logs) {
                writer.write(String.format("%s|%s|%s|%s\n",
                    log.getTime(), log.getType(), log.getOperator(), log.getDetail()));
            }
            writer.close();
        } catch (IOException e) {
            System.out.println("保存日志数据失败: " + e.getMessage());
        }
    }
    
    private static void loadLogs() {
        try {
            File file = new File(LOG_FILE);
            if (!file.exists()) {
                return;
            }
            
            Scanner fileScanner = new Scanner(file);
            while (fileScanner.hasNextLine()) {
                String line = fileScanner.nextLine();
                String[] parts = line.split("\\|");
                if (parts.length >= 4) {
                    String time = parts[0];
                    String type = parts[1];
                    String operator = parts[2];
                    String detail = parts[3];
                    logs.add(new LogEntry(time, type, operator, detail));
                }
            }
            fileScanner.close();
        } catch (IOException e) {
            System.out.println("加载日志数据失败: " + e.getMessage());
        }
    }
} 